package com.nowcoder.community.service.impl;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.util.RedisKeyUtil;
import com.nowcoder.community.util.SensitiveFilter;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 花木凋零成兰
 * @date 2024/3/4 21:06
 */
@Service
@Slf4j(topic = "DiscussPostService.class")
public class DiscussPostServiceImpl implements DiscussPostService {

    @Resource
    private DiscussPostMapper discussPostMapper;

    @Resource
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * Caffeine核心接口：Cache, LoadingCache, AsyncLoadingCache
     */

    /**
     * 帖子列表缓存
     */
    private LoadingCache<String, List<DiscussPost>> postListCache;

    /**
     * 帖子总数缓存
     */
    private LoadingCache<Integer, Integer> postRowsCache;

    @PostConstruct
    public void init() {
        // 初始化帖子列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Override
                    public @Nullable List<DiscussPost> load(@NonNull String key) throws Exception {
                        if (key.isEmpty()) {
                            throw new IllegalArgumentException("参数错误!");
                        }
                        String[] params = key.split(":");
                        if (params.length != 2) {
                            throw new IllegalArgumentException("参数错误!");
                        }
                        int offset = Integer.parseInt(params[0]);
                        int limit = Integer.parseInt(params[1]);

                        // 可添加二级缓存 Redis -> mysql
                        // 首先查询Redis中是否存在数据
                        String redisKey = RedisKeyUtil.getDiscussPostListKey(key);
                        List<DiscussPost> list;
                        if (redisTemplate.hasKey(redisKey)) {   // 若Redis中存在key 则查询redis
                            log.warn("load post list form Redis.");
                            list = (List<DiscussPost>) redisTemplate.opsForValue().get(redisKey);
                            return list;
                        } else {    // 若Redis中不存在 再到MySQL中查询
                            log.debug("load post list from DB.");
                            list = discussPostMapper.selectDiscussPosts(0, offset, limit, 1);
                            // 缓存到Redis中
                            redisTemplate.opsForValue().set(redisKey, list);
                            redisTemplate.expire(redisKey, 180, TimeUnit.SECONDS);   // 并设置Redis缓存有效时间
                            return list;    // 再返回到本地缓存
                        }

                    }
                });
        // 初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull Integer key) throws Exception {
                        // 可添加二级缓存 Redis -> mysql
                        // 首先查询Redis中是否存在数据
                        String redisKey = RedisKeyUtil.getDiscussPostRowsKey(key);
                        int rows;
                        if (redisTemplate.hasKey(redisKey)) {   // 若Redis中存在key 则查询redis
                            log.warn("load post list form Redis.");
                            rows = (int) redisTemplate.opsForValue().get(redisKey);
                            return rows;
                        } else {    // 若Redis中不存在 再到MySQL中查询
                            log.debug("load post list from DB.");
                            rows = discussPostMapper.selectDiscussPostRows(key);
                            // 缓存到Redis中
                            redisTemplate.opsForValue().set(redisKey, rows);
                            redisTemplate.expire(redisKey, 180, TimeUnit.SECONDS);   // 并设置Redis缓存有效时间
                            return rows;    // 再返回到本地缓存
                        }
                    }
                });

    }

    /**
     * 分页查询 帖子
     *
     * @param userId
     * @param offset
     * @param limit
     * @param orderMode
     * @return
     */
    @Override
    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode) {

        if (userId == 0 && orderMode == 1) {    // 主页查看热门帖子时 才获取缓存
            return postListCache.get(offset + ":" + limit);
        }
        log.debug("load post list from DB.");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);
    }

    /**
     * 查询用户帖子总数
     * @param userId
     * @return
     */
    @Override
    public int findDiscussPostRows(int userId) {

        if (userId == 0) {
            return postRowsCache.get(userId);
        }
        log.debug("load post rows from DB.");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    /**
     * 发布帖子
     * @param discussPost
     * @return
     */
    @Override
    public int addDiscussPost(DiscussPost discussPost) {
        if (discussPost == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 转义HTML标记
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));

        // 过滤敏感词
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));

        return discussPostMapper.insertDiscussPost(discussPost);
    }

    /**
     * 批量插入帖子数据
     * @param discussPosts
     */
    @Override
    public void addBatchDiscussPost(List<DiscussPost> discussPosts) {
        if (discussPosts == null || discussPosts.isEmpty()) {
            log.error("批量插入帖子列表不能为空!");
        }
        discussPostMapper.insertBatchDiscussPost(discussPosts);
    }

    /**
     * 根据帖子id查询帖子
     * @param id 帖子id
     * @return DiscussPost
     */
    @Override
    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    /**
     * 更新帖子 评论数目
     * @param id
     * @param commentCount
     * @return
     */
    @Override
    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    /**
     * 更改帖子类型：0-普通， 1-置顶
     * @param id 帖子id
     * @param type 修改为类型
     * @return
     */
    @Override
    public int updateType(int id, int type) {
        return discussPostMapper.updateType(id, type);
    }

    /**
     * 修改帖子状态：0-正常; 1-精华; 2-拉黑
     * @param id
     * @param status
     * @return
     */
    @Override
    public int updateStatus(int id, int status) {
        return discussPostMapper.updateStatus(id, status);
    }

    /**
     * 更新帖子分数
     * @param id
     * @param score
     * @return
     */
    @Override
    public int updateScore(int id, double score) {
        return discussPostMapper.updateScore(id, score);
    }

}
